package com.bupt.kgplatform.common;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CsvUtils {
    public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) {

        InputStreamReader in = null;
        try {
            in = new InputStreamReader(file.getInputStream(), "GBK");  // UTF-8为解析时用的编码格式，csv文件也需要定义为UTF-8编码格式，解析格式根据csv文件的编码格式而定，csv默认编码格式为GBK
        } catch (IOException e) {
            log.error("读取csv文件失败！ ---> " + e.getMessage());
        }
        HeaderColumnNameTranslateMappingStrategy<T> mappingStrategy = new HeaderColumnNameTranslateMappingStrategy<>();
        mappingStrategy.setType(clazz);
        Map map = new HashMap();
        map.put("文本名称", "textname");
        map.put("文本作者", "author");
        map.put("文本描述", "description");
        map.put("文本内容", "text");

        mappingStrategy.setColumnMapping(map);
        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in)
                .withSeparator(',')
                .withIgnoreQuotations(true)
                .withMappingStrategy(mappingStrategy)
                .build();
        return csvToBean.parse();

    }
}
